﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using MINERP.DAL;
using MINERP.BLL.Common;
using MINERP.COM;
using System.Drawing;
using MINERP.MODEL.AutoOrder_Fuji;
using FastReport;
using System.Windows.Forms;
using Leadtools;
using Leadtools.Codecs;
using System.Drawing.Drawing2D;
namespace MINERP.BLL.AutoOrder
{
    /// <summary>
    /// 读取富士的自动开单项目
    /// </summary>
    public class ReadFujiXML
    {
        const string SHOPNAME = "F富士影美全印馆";
        const int PRIORITY = 1;//远程开单的默认加急级别
        const float INCHTOCM = 2.54f;//英寸到CM
        const float INCHTOMM = 25.4f;//英寸到MM

        public string xmlPath { get; set; }//XML文档的路径

        Report rp = new Report();
        List<JobSheetSummary_Delivery_Fuji_Info> listT = new List<JobSheetSummary_Delivery_Fuji_Info>();
        Stream deliveryStream = null;//用于保存发货报表的信息

        public ReadFujiXML(string xpath)
        {
            xmlPath = xpath;
            rp.Load(Application.StartupPath + "\\Report\\巨星发货单.frx");
        }

        public bool ResolveOrderXML(out string strMsg)
        {
            return ResolveOrderXML(xmlPath, out strMsg);
        }

        /// <summary>
        /// 解析XML文档
        /// </summary>
        /// <param name="strMsg">如果遇到错误或是异常等返回的文本信息，用于调用方去显示</param>
        /// <returns>-1:XML路径为空;-2:XML文档找不到</returns>
        public bool ResolveOrderXML(string xPath, out string strErrMsg)
        {
            strErrMsg = string.Empty;
            newSampleYPDBEntities db = new newSampleYPDBEntities();

            if (string.IsNullOrEmpty(xPath))
            {
                strErrMsg = "路径为空";
                return false;
            }

            if (!File.Exists(xPath))
            {
                strErrMsg = "文件不存在\n" + xPath;
                return false;
            }
            XmlDocument xml = new XmlDocument();
            try
            {
                xml.Load(xPath);
            }
            catch (Exception ex)
            {
                strErrMsg = ex.Message;
                return false;
            }
            //每一个orderBag都会有一个发货单,这些发货信息的具体内部分别放在不同的地方，即要在下面解析的各个坏节都去收集整理
            JobSheetSummary_Delivery_Fuji_Info deliveryInfo = new JobSheetSummary_Delivery_Fuji_Info();
            deliveryInfo.ArticleList = new List<ArticleInfo>();

            Tb_OrderBag newOrderBag = CreateNewOrderBag(db, xml, deliveryInfo, out strErrMsg);//orderBag
            if (newOrderBag == null)
            {
                return false;
            }
            //客人名称
            string ctmName = newOrderBag.CustomAddress.FirstOrDefault().Lastname + newOrderBag.CustomAddress.FirstOrDefault().Firstname;
            XmlNode products = xml.SelectSingleNode(@"/order/products");
            bool isNeedPrintIndex = false;
            int intDSC_PRINTCount = 0;
            foreach (XmlNode product in products.ChildNodes)//代表每一种产品s
            {
                string strExportName = product.Attributes["exportname"].Value.Trim();
                if (strExportName == "INDEXPRINT")//特殊处理代表，此定单包是要打印索引的，所以此定单包的产口的备注上都即要写上索引二字
                {
                    isNeedPrintIndex = true;
                    //continue;
                }
               
                Tb_Product tb_product = db.Tb_Product.FirstOrDefault(p => p.ProductName == strExportName && p.Status == 1);
                if (tb_product == null)
                {
                    strErrMsg = "产品库中没有该产品，请先添加后重新开单！\n" + strExportName;
                    return false;
                }

                //先检查这些产品是否为FUJI制定过价格，或是选上了
                if (!newOrderBag.Shop.Shop_Product_Price.IsLoaded)
                {
                    newOrderBag.Shop.Shop_Product_Price.Load();
                }
                if (newOrderBag.Shop.Shop_Product_Price.ToList().FirstOrDefault(spp => spp.ProductId == tb_product.ProuctId) == null)
                {
                    strErrMsg = newOrderBag.Shop.shopName + "没有生产此产品的权限，请从后台添加," + tb_product.ProductName;
                    return false;
                }
                int intCurrProductIndexPrintCount = 0;
                List<orderInfo> orderList = CreateNewOrderInfoList(db, xml, product, tb_product, ctmName, deliveryInfo, out strErrMsg, out intCurrProductIndexPrintCount);
                intDSC_PRINTCount += intCurrProductIndexPrintCount;//累计需要打印索引的照片的数量

                if (orderList == null || orderList.Count < 1)//在构建orderinfo时出错
                {
                    return false;
                }

                //每个产品
                foreach (var oi in orderList)
                {
                    newOrderBag.orderInfo.Add(oi);
                }
            }

            //添加整个定单的总金额，以及运费金额     
            decimal shippingPrice, totalPrice;

            GetShippingAndTotalPrice(xml, out shippingPrice, out totalPrice);
            deliveryInfo.ShippingFee = shippingPrice;
            deliveryInfo.TotalPrice = totalPrice;

            newOrderBag.CustomAddress.FirstOrDefault().DeliveryReportStream = CreateReportStream(deliveryInfo);

            newOrderBag.FetchTime = Convert.ToDateTime(products.ChildNodes[0].Attributes["delivery-date"].Value.Trim() + " " + products.ChildNodes[0].Attributes["delivery-time"].Value.Trim());
            newOrderBag.CompleteTime = newOrderBag.FetchTime;

            if (MovePicToOrderedFolder(newOrderBag, out strErrMsg))//移动成功，则将数据添加到数据库,并将XML也移动到开单目录下           
            //if (true)
            {
                try
                {
                    bool IsFirstOne = true;//只在定单的第一个产品上给运费付值
                    foreach (var foi in deliveryInfo.ArticleList)
                    {
                        Tb_FujOrderInfo newFoi = new Tb_FujOrderInfo()
                        {
                            CompanyName = deliveryInfo.CompanyName,
                            ProductName = foi.ProductName,
                            OrderNum = deliveryInfo.Oi_OrderNum,
                            Discount = foi.Discount,
                            DeliveryCompanyName = deliveryInfo.Oi_ShippingCompanyName,
                            OrderDateTime = deliveryInfo.Oi_OrderDate,
                            PaymentInfo = deliveryInfo.Oi_PayMentName,
                            UnitPrice = foi.UnitPrice,
                            TotalPriceAfterDiscount = foi.TotalPriceAfterDiscount,
                            TotalPriceBeforeDiscount = foi.TotalPriceBeforeDiscount,
                            ProductNum = foi.Quantity
                        };
                        if (IsFirstOne)
                        {
                            newFoi.ShippingFee = deliveryInfo.ShippingFee;
                            IsFirstOne = false;
                        }
                        else
                        {
                            newFoi.ShippingFee = 0;
                        }
                        if (foi.ProductName.Contains("INDEXPRINT"))
                        {
                            //计算需要打印索引的数量每张索引可以打40张小图
                            if (intDSC_PRINTCount % 40 == 0)
                            {
                                newFoi.ProductNum = intDSC_PRINTCount / 40;
                            }
                            else
                            {
                                newFoi.ProductNum = intDSC_PRINTCount / 40+1;
                            }
 
                        }
                        db.AddToTb_FujOrderInfo(newFoi);
                    }

                    if (newOrderBag.CustomAddress.FirstOrDefault().TotalPrice == -2)//即货到付款的,需要给总价付值
                    {
                        newOrderBag.CustomAddress.FirstOrDefault().TotalPrice = deliveryInfo.TotalPrice;
                    }

                    db.AddToTb_OrderBag(newOrderBag);

                    db.SaveChanges();
                    #region//更新orderinfo、photoinfo、tb_orderbag中的对应的CODE
                    foreach (var oi in newOrderBag.orderInfo)
                    {
                        oi.OrderProductCode = "2" + oi.OrderProductId.ToString().PadLeft(9, '0');
                        if (isNeedPrintIndex)
                        {
                            oi.Remark += "打印索引";
                        }
                        if (oi.OrderProductName.Contains("INDEXPRINT"))
                        {
                            //计算需要打印索引的数量每张索引可以打40张小图
                            if (intDSC_PRINTCount % 40 == 0)
                            {
                               oi.productNum = intDSC_PRINTCount / 40;
                            }
                            else
                            {
                                oi.productNum = intDSC_PRINTCount / 40 + 1;
                            }
                        }
                        foreach (var pi in oi.photoInfo)
                        {
                            pi.PhotoBarCode = "3" + pi.photoId.ToString().PadLeft(9, '0');
                        }
                    }
                    newOrderBag.BagCode = "1" + newOrderBag.OrderBagId.ToString().PadLeft(9, '0');
                    db.SaveChanges();
                    #endregion
                    return true;
                }
                catch (Exception ex)
                {
                    strErrMsg = "在向数据库保存时出错：\n" + ex.Message;
                    return false;
                }
            }
            else//如果没有成功
            {
                return false;
            }
        }

        #region help methods
        /// <summary>
        /// 得到发货价和定单的总价格
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="shippingPrice"></param>
        /// <param name="totalPrice"></param>
        private void GetShippingAndTotalPrice(XmlDocument xml, out decimal shippingPrice, out decimal totalPrice)
        {
            shippingPrice = 0;
            totalPrice = 0;

            XmlNodeList pricesNodeList = xml.SelectNodes("/order/prices");//得到价格的元素字段
            bool original, result;
            foreach (XmlNode price in pricesNodeList)
            {
                original = Convert.ToBoolean(price.Attributes["original"].Value.Trim());
                result = Convert.ToBoolean(price.Attributes["result"].Value.Trim());

                if (result)//读取totalPrice
                {
                    XmlNode totalPriceNode = price.SelectSingleNode("totalprice");
                    if (totalPriceNode != null)
                    {
                        totalPrice = Convert.ToDecimal(totalPriceNode.Attributes["gross"].Value);
                    }

                    //读取shippingPrice
                    XmlNode shippingFeePrice = price.SelectSingleNode(@"shippingprice/totalprice");
                    if (shippingFeePrice != null)
                    {
                        shippingPrice = Convert.ToDecimal(shippingFeePrice.Attributes["gross"].Value);
                    }
                }

                //if (!original && result)//读取shippingPrice
                //{
                //    XmlNode shippingFeePrice = price.SelectSingleNode(@"shippingprice/totalprice");
                //    if (shippingFeePrice != null)
                //    {
                //        shippingPrice = Convert.ToDecimal(shippingFeePrice.Attributes["gross"].Value);
                //    }
                //}
            }
        }

        /// <summary>
        /// 预计完成时间需重新计算
        /// </summary>
        /// <param name="db"></param>
        /// <param name="xml"></param>
        /// <returns></returns>
        private Tb_OrderBag CreateNewOrderBag(newSampleYPDBEntities db, XmlDocument xml, JobSheetSummary_Delivery_Fuji_Info deliveryInfo, out string errMsg)
        {
            errMsg = string.Empty;
            Tb_OrderBag newOrderBag = new Tb_OrderBag();
            ShopBLL sBll = new ShopBLL();

            users editU = db.users.FirstOrDefault();
            if (editU == null)
            {
                errMsg = "系统中还没有建立任何相关的用户，请先建立用户再开单！";
                return null;
            }

            Shop curShop = sBll.GetShopByShopName(SHOPNAME, db);
            if (curShop == null)
            {
                errMsg = "还未建立商户：" + SHOPNAME + " 请先建立此商户后再开单！";
                return null;
            }

            try
            {
                //delivery_oi
                deliveryInfo.Oi_OrderNum = xml.SelectSingleNode(@"/order").Attributes["id"].Value;
                deliveryInfo.Oi_OrderDate = Convert.ToDateTime(xml.SelectSingleNode("/order/processor").Attributes["date"].Value + " " + xml.SelectSingleNode("/order/processor").Attributes["time"].Value);

                //orderbag
                newOrderBag.BagName = xml.SelectSingleNode(@"/order").Attributes["id"].Value + "_富士网单";//取order的ID
                newOrderBag.CompleteTime = DateTime.Now;
                newOrderBag.EditUserID = editU.userID;
                newOrderBag.FetchTime = DateTime.Now;
                newOrderBag.OrderTime = deliveryInfo.Oi_OrderDate;
                newOrderBag.Priority = PRIORITY;
                newOrderBag.Remark = xml.SelectSingleNode(@"/order").Attributes["id"].Value + "_富士网单";
                newOrderBag.Shop = curShop;
                newOrderBag.Status = (int)OrderBagStatus.Doing;
                newOrderBag.Type = (int)OrderBagType.RemoteOrder;
                newOrderBag.users = editU;
                newOrderBag.BagCode = "00";
            }
            catch (Exception ex)
            {
                errMsg = "在构建orderBag时出错：" + ex.Message;
                return null;
            }

            XmlNode shipNode = xml.SelectSingleNode("/order/shipping");
            XmlNodeList addressList = xml.SelectNodes("/order/addresses/address");
            //XmlNode addressNode = xml.SelectSingleNode(@"/order/addresses/address");//找到第一个arrderss，这里会有二个address，第二个address是用来发货的地址
            if (addressList.Count < 1)
            {
                errMsg = "在order.xml中没有发现address信息，请确认修改后重试!";
                return null;
            }
            XmlNode FromAddressNode = addressList[0];
            XmlNode DeliveryToAddress;
            if (addressList.Count == 1)
            {
                //哪果只有一个address，查看一下是否还有location元素，如果有则为发送地方，如果无则用第一个address
                //DeliveryToAddress = xml.SelectSingleNode("/order/addresses/address");
                //if (DeliveryToAddress == null)
                //{
                DeliveryToAddress = FromAddressNode;
                //}
            }
            else
            {
                DeliveryToAddress = addressList[1];
            }

            XmlNode payMentNode = xml.SelectSingleNode("/order/payment");//付款类型

            ShippingCompany ship = CreateShipping(db, shipNode, out errMsg);
            if (ship != null)
            {
                CustomAddress addr;
                try
                {
                    //deliveryinfo_frm_userid
                    deliveryInfo.OiFr_UserID = xml.SelectSingleNode(@"/order/user").Attributes["id"].Value;
                    //delivery_DETO
                    deliveryInfo.DeTo_Address = GetProvienceNameByCode(DeliveryToAddress.Attributes["province"].Value) + DeliveryToAddress.Attributes["city"].Value + DeliveryToAddress.Attributes["city-part"].Value + DeliveryToAddress.Attributes["street"].Value;
                    deliveryInfo.DeTo_FamilyName = DeliveryToAddress.Attributes["lastname"].Value;
                    deliveryInfo.DeTo_GivenName = DeliveryToAddress.Attributes["firstname"].Value;
                    deliveryInfo.DeTo_MobilePhone = DeliveryToAddress.Attributes["mobile"].Value.Trim();//这里的字段不确定 
                    deliveryInfo.CompanyName = FromAddressNode.Attributes["company"] == null ? "" : FromAddressNode.Attributes["company"].Value;

                    deliveryInfo.OiFr_FamilyName = FromAddressNode.Attributes["lastname"] == null ? "" : FromAddressNode.Attributes["lastname"].Value;
                    deliveryInfo.OiFr_GivenName = FromAddressNode.Attributes["firstname"] == null ? "" : FromAddressNode.Attributes["firstname"].Value;
                    deliveryInfo.OiFr_MobilePhone = FromAddressNode.Attributes["mobile"] == null ? "" : FromAddressNode.Attributes["mobile"].Value.Trim();//MobilePhoneNum字段还不确定
                    deliveryInfo.OiFr_Tel = FromAddressNode.Attributes["phone"] == null ? "" : FromAddressNode.Attributes["phone"].Value.Trim();
                    if (string.IsNullOrEmpty(deliveryInfo.OiFr_Tel))
                    {
                        deliveryInfo.OiFr_Tel = deliveryInfo.OiFr_MobilePhone;
                    }

                    addr = CreateCtmAddr(db, DeliveryToAddress);//这里是收费人的地址，需要用这些信息打印快递单
                    if (string.IsNullOrEmpty(addr.Phone.Trim()))
                    {
                        addr.Phone = addr.MobilePhoneNum;
                    }
                }
                catch (Exception ex)
                {
                    errMsg = "在构建CustomAddress时出错：" + ex.Message;
                    return null;
                }


                int payMentCode = 0;//从order.xml取出来的ID在数据库中的名字中paymentcode,第二个就是要从数据库中取出来的ID
                CustomerPaymentInfo payMentInfo = null;

                if (payMentNode == null || payMentNode.Attributes["id"] == null)
                {
                    errMsg = "在order.xml中没有找到paymentElement和ID属性";
                    return null;
                }
                else
                {
                    if (!Int32.TryParse(payMentNode.Attributes["id"].Value, out payMentCode))
                    {
                        errMsg = "payMent中的id无效";
                        return null;
                    }
                }

                if (GetPayMentIdByName(db, payMentCode, out payMentInfo, out errMsg))
                {
                    addr.paymentID = payMentInfo.paymentID;
                    if (payMentCode == 6)//货到付款
                    {
                        addr.TotalPrice = -2;//表示需要进行符值
                    }else
                    //if (payMentCode == 22)//分 到店取和快递,即将到哪个店的信息写到报表上
                    {
                        //deliveryInfo
                        try
                        {
                            XmlNode ShopNode = xml.SelectSingleNode("/order/shipping/shipping-type");
                            string shopType = ShopNode.InnerText;
                            if ("shop".ToUpper().Equals(shopType.ToUpper()))//到店取货
                            {
                                try
                                {
                                    XmlNode LocationNode = xml.SelectSingleNode("/order/addresses/location");
                                    deliveryInfo.ShopAddr = "地址:" + (LocationNode.Attributes["street"] == null ? "没写地址" : LocationNode.Attributes["street"].Value) + (LocationNode.Attributes["house-number"]==null?"没写门牌号":LocationNode.Attributes["house-number"].Value);
                                    deliveryInfo.ShopArea = "地区:" + LocationNode.Attributes["city"] == null ? "没写地区名" : LocationNode.Attributes["city"].Value;
                                    deliveryInfo.ShopName = "店名:" + LocationNode.Attributes["company"] == null ? "没写店名" : LocationNode.Attributes["company"].Value;
                                    deliveryInfo.ShopTel = "电话:" + LocationNode.Attributes["phone"] == null ? "没写电话" : LocationNode.Attributes["phone"].Value;
                                }
                                catch (Exception ex)
                                {
                                    errMsg = "在构建到店取货信息时出错:" + ex.Message;
                                    return null;
                                }
                            }
                        }
                        catch
                        {
                            errMsg = "解析XML时出错：缺少送货方式";
                            return null;
                        }


                    }
                }
                else
                {
                    return null;
                }
                //delivery_oi
                deliveryInfo.Oi_ShippingCompanyName = ship.ShippingCompanyName;
                deliveryInfo.Oi_PayMentName = payMentInfo.paymentName;
                addr.ShippingCompany = ship;

                newOrderBag.CustomAddress.Add(addr);
            }
            else
            {
                return null;
            }
            return newOrderBag;
        }

        /// <summary>
        /// 临时的根据省份的代号得到省份的名称
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public string GetProvienceNameByCode(string code)
        {
            string pName = string.Empty;
            switch (code.Trim())
            {
                case "11": pName = "北京";
                    break;
                case "12": pName = "天津";
                    break;
                case "13": pName = "河北";
                    break;
                case "14": pName = "山西";
                    break;
                case "15": pName = "内蒙古";
                    break;
                case "21": pName = "辽宁";
                    break;
                case "22": pName = "吉林";
                    break;
                case "23": pName = "黑龙江";
                    break;
                case "31": pName = "上海";
                    break;
                case "32": pName = "江苏";
                    break;
                case "33": pName = "浙江";
                    break;
                case "34": pName = "安徽";
                    break;
                case "35": pName = "福建";
                    break;
                case "36": pName = "江西";
                    break;
                case "37": pName = "山东";
                    break;
                case "41": pName = "河南";
                    break;
                case "42": pName = "湖北";
                    break;
                case "43": pName = "湖南";
                    break;
                case "44": pName = "广东";
                    break;
                case "45": pName = "广西";
                    break;
                case "46": pName = "海南";
                    break;
                case "50": pName = "重庆";
                    break;
                case "51": pName = "四川";
                    break;
                case "52": pName = "贵州";
                    break;
                case "53": pName = "云南";
                    break;
                case "54": pName = "西藏";
                    break;
                case "61": pName = "陕西";
                    break;
                case "62": pName = "甘肃";
                    break;
                case "63": pName = "青海";
                    break;
                case "64": pName = "宁夏";
                    break;
                case "65": pName = "新彊";
                    break;
                case "71": pName = "台湾";
                    break;
                case "91": pName = "香港";
                    break;
                case "92": pName = "澳门";
                    break;
                default: pName = code;
                    break;
            }
            return pName;
        }

        /// <summary>
        /// 根据发货的实体得到相应的报表流
        /// </summary>
        /// <param name="deliveryInfo"></param>
        /// <returns></returns>
        private byte[] CreateReportStream(JobSheetSummary_Delivery_Fuji_Info deliveryInfo)
        {
            listT.Clear();
            listT.Add(deliveryInfo);
            rp.RegisterData(listT, "diverInfo");
            //设计时使用
            //rp.Design();
            //rp.Dispose();

            using (MemoryStream deliveryStreamT = new MemoryStream())
            {
                if (rp.Prepare())
                {
                    //rp.Show();
                    rp.SavePrepared(deliveryStreamT);
                    //rp.SavePrepared(Application.StartupPath + "\\tempPRX.fpx");//测试用 
                }
                return deliveryStreamT.ToArray();
            }
        }

        /// <summary>
        /// 根据从order.xml读取出来的付款ID得到付款的相对应的中文件名称
        /// </summary>
        /// <param name="db"></param>
        /// <param name="payMentName"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        private bool GetPayMentIdByName(newSampleYPDBEntities db, int payMentCode, out CustomerPaymentInfo PayeMentInfo, out string errMsg)
        {
            PayeMentInfo = null;//返回从数据库中取出的自增ID那一栏
            errMsg = string.Empty;
            CustomerPaymentInfo payInfo = db.CustomerPaymentInfo.FirstOrDefault(p => p.paymentCode == payMentCode);
            if (payInfo == null)
            {
                errMsg = string.Format("此{0}付款ID没有找到对应的付款类型，请添加后再试!", payMentCode);
                return false;
            }
            else
            {
                PayeMentInfo = payInfo;
                return true;
            }
        }

        /// <summary>
        /// 得到用户选定的快递商信息
        /// </summary>
        /// <param name="db"></param>
        /// <returns>如果返回NULL则表示XML中没有相应的</returns>
        private ShippingCompany CreateShipping(newSampleYPDBEntities db, XmlNode shipNode, out string errMsg)
        {
            //这里应该根据SHIP中的内容来查找相应的快递公司
            errMsg = string.Empty;
            string shipAlaisName = shipNode.SelectSingleNode("shipping-type").InnerText;
            if (string.IsNullOrEmpty(shipAlaisName))
            {
                errMsg = "在order.xml中没有找到相应的发货信息";
                return null;//出错
            }
            ShippingCompany r = db.ShippingCompany.FirstOrDefault(s => s.Alias == shipAlaisName);
            if (r == null)
            {
                errMsg = "还未添加该快速商" + shipAlaisName;
                return null;
            }

            return r;
        }

        /// <summary>
        /// 创建定单(客人)的发货信息
        /// </summary>
        /// <param name="db"></param>
        /// <param name="addrNode"></param>
        /// <returns></returns>
        private CustomAddress CreateCtmAddr(newSampleYPDBEntities db, XmlNode addrNode)
        {
            //delivery_orderFrom,这里少了一个uid
            //deliveryInfo.OiFr_FamilyName = addrNode.Attributes["lastname"] == null ? "" : addrNode.Attributes["lastname"].Value;
            //deliveryInfo.OiFr_GivenName = addrNode.Attributes["firstname"] == null ? "" : addrNode.Attributes["firstname"].Value;
            //deliveryInfo.OiFr_MobilePhone = addrNode.Attributes["mobile"] == null ? "" : addrNode.Attributes["mobile"].Value;//MobilePhoneNum字段还不确定
            //deliveryInfo.OiFr_Tel = addrNode.Attributes["phone"] == null ? "" : addrNode.Attributes["phone"].Value;

            return new CustomAddress()
            {
                Area = addrNode.Attributes["area"] == null ? "" : addrNode.Attributes["area"].Value,
                City = addrNode.Attributes["city"] == null ? "" : addrNode.Attributes["city"].Value,
                CityPart = addrNode.Attributes["city-part"] == null ? "" : addrNode.Attributes["city-part"].Value,
                Company = addrNode.Attributes["company"] == null ? "" : addrNode.Attributes["company"].Value,
                CountryCode = addrNode.Attributes["country-code"] == null ? "" : addrNode.Attributes["country-code"].Value,
                Firstname = addrNode.Attributes["firstname"] == null ? "" : addrNode.Attributes["firstname"].Value,
                Lastname = addrNode.Attributes["lastname"] == null ? "" : addrNode.Attributes["lastname"].Value,
                Phone = addrNode.Attributes["phone"] == null ? "" : addrNode.Attributes["phone"].Value,
                Province = addrNode.Attributes["province"] == null ? "无省份" : GetProvienceNameByCode(addrNode.Attributes["province"].Value),
                Salutation = addrNode.Attributes["salutation"] == null ? "" : addrNode.Attributes["salutation"].Value,
                Street = addrNode.Attributes["street"] == null ? "" : addrNode.Attributes["street"].Value,
                Zip = addrNode.Attributes["zip"] == null ? "" : addrNode.Attributes["zip"].Value,
                MobilePhoneNum = addrNode.Attributes["mobile"] == null ? "" : addrNode.Attributes["mobile"].Value,//MobilePhoneNum字段还不确定
                ShippingStatusContext = "",
                TotalPrice = -1//默认都不是货到付款
            };

        }

        /// <summary>
        /// 得到某一产品的折扣前、折扣、折扣后的三种价格
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="product"></param>
        /// <param name="TotalPriceBeforeDiscount"></param>
        /// <param name="discount"></param>
        /// <param name="TotalPriceAfterDiscount"></param>
        /// <param name="UnitPrice"></param>
        private void GetBeforMoney(XmlDocument xml, XmlNode product, string productID, out decimal TotalPriceBeforeDiscount, out decimal discount, out decimal TotalPriceAfterDiscount, out decimal UnitPrice, out bool IsUnitDiscount)
        {
            IsUnitDiscount = false;//是否整体打折
            TotalPriceBeforeDiscount = 0;
            discount = 0;
            TotalPriceAfterDiscount = 0;
            UnitPrice = 0;

            int orderItemId = Convert.ToInt32(product.Attributes["id"].Value.Trim());

            XmlNodeList pricesNodeList = xml.SelectNodes("/order/prices");//得到价格的元素字段
            bool original, result;
            foreach (XmlNode price in pricesNodeList)
            {
                original = Convert.ToBoolean(price.Attributes["original"].Value.Trim());
                result = Convert.ToBoolean(price.Attributes["result"].Value.Trim());

                if (original && result)//无折扣
                {
                    bool isFindInOrderItem = false;
                    foreach (XmlNode orderItemPrice in price.SelectNodes(@"orderitemprices/orderitemprice"))
                    {
                        var orderIdNode = orderItemPrice.SelectSingleNode("ref-orderitem");
                        if (orderIdNode != null)
                        {
                            if (Convert.ToInt32(orderIdNode.Attributes["id"].Value.Trim()) == orderItemId)//找到了该产品
                            {
                                TotalPriceBeforeDiscount = Convert.ToDecimal(orderItemPrice.SelectSingleNode("price").Attributes["gross"].Value);
                                discount = 0;
                                TotalPriceAfterDiscount = TotalPriceBeforeDiscount;

                                UnitPrice = Convert.ToDecimal(orderItemPrice.SelectSingleNode("unitprice").Attributes["gross"].Value);

                                isFindInOrderItem = true;
                                break;
                            }
                        }
                    }

                    if (!isFindInOrderItem)//即在orderItems中没有找到相应的记录,则从ProductPrices中寻找
                    {
                        foreach (XmlNode orderItemPrice in price.SelectNodes(@"productprices/productprice"))
                        {
                            var orderIdNode = orderItemPrice.SelectSingleNode("ref-product");
                            if (orderIdNode != null)
                            {
                                if (orderIdNode.Attributes["id"].Value.Trim() == productID)//找到了该产品
                                {
                                    TotalPriceBeforeDiscount = Convert.ToDecimal(orderItemPrice.SelectSingleNode("price").Attributes["gross"].Value);
                                    discount = 0;
                                    TotalPriceAfterDiscount = TotalPriceBeforeDiscount;
                                    UnitPrice = 0;
                                    //UnitPrice = Convert.ToDecimal(orderItemPrice.SelectSingleNode("unitprice").Attributes["gross"].Value);
                                    IsUnitDiscount = true;
                                    isFindInOrderItem = true;
                                    break;
                                }
                            }
                        }
                    }

                    break;
                }
                else if (original && !result)//折扣前价
                {
                    bool isFindInOrderItem = false;
                    foreach (XmlNode orderItemPrice in price.SelectNodes(@"orderitemprices/orderitemprice"))
                    {
                        var orderIdNode = orderItemPrice.SelectSingleNode("ref-orderitem");
                        if (orderIdNode != null)
                        {
                            if (Convert.ToInt32(orderIdNode.Attributes["id"].Value.Trim()) == orderItemId)//找到了该产品
                            {
                                TotalPriceBeforeDiscount = Convert.ToDecimal(orderItemPrice.SelectSingleNode("price").Attributes["gross"].Value);

                                UnitPrice = Convert.ToDecimal(orderItemPrice.SelectSingleNode("unitprice").Attributes["gross"].Value);
                                isFindInOrderItem = true;
                                break;
                            }
                        }
                    }

                    if (!isFindInOrderItem)//即在orderItems中没有找到相应的记录,则从ProductPrices中寻找
                    {
                        foreach (XmlNode orderItemPrice in price.SelectNodes(@"productprices/productprice"))
                        {
                            var orderIdNode = orderItemPrice.SelectSingleNode("ref-product");
                            if (orderIdNode != null)
                            {
                                if (orderIdNode.Attributes["id"].Value.Trim() == productID)//找到了该产品
                                {
                                    TotalPriceBeforeDiscount = Convert.ToDecimal(orderItemPrice.SelectSingleNode("price").Attributes["gross"].Value);

                                    UnitPrice = 0;
                                    IsUnitDiscount = true;
                                    isFindInOrderItem = true;
                                    break;
                                }
                            }
                        }
                    }
                }
                else if (!original && !result)//折扣价
                {
                    bool isFindInOrderItem = false;
                    foreach (XmlNode orderItemPrice in price.SelectNodes(@"orderitemprices/orderitemprice"))
                    {
                        var orderIdNode = orderItemPrice.SelectSingleNode("ref-orderitem");
                        if (orderIdNode != null)
                        {
                            if (Convert.ToInt32(orderIdNode.Attributes["id"].Value.Trim()) == orderItemId)//找到了该产品
                            {
                                discount = Convert.ToDecimal(orderItemPrice.SelectSingleNode("price").Attributes["gross"].Value);
                                isFindInOrderItem = true;
                                break;
                            }
                        }
                    }
                    if (price.SelectNodes(@"orderitemprices/orderitemprice").Count > 0)//只在有一个有,就不算是整体折扣
                    {
                        isFindInOrderItem = true;
                    }

                    if (!isFindInOrderItem)//即在orderItems中没有找到相应的记录,则从ProductPrices中寻找
                    {
                        foreach (XmlNode orderItemPrice in price.SelectNodes(@"productprices/productprice"))
                        {
                            var orderIdNode = orderItemPrice.SelectSingleNode("ref-product");
                            if (orderIdNode != null)
                            {
                                if (orderIdNode.Attributes["id"].Value.Trim() == productID)//找到了该产品
                                {
                                    discount = Convert.ToDecimal(orderItemPrice.SelectSingleNode("price").Attributes["gross"].Value);
                                    isFindInOrderItem = true;
                                    IsUnitDiscount = true;
                                    break;
                                }
                            }
                        }
                    }
                }
                else if (!original && result)//折扣后价
                {
                    bool isFindInOrderItem = false;
                    foreach (XmlNode orderItemPrice in price.SelectNodes(@"orderitemprices/orderitemprice"))
                    {
                        var orderIdNode = orderItemPrice.SelectSingleNode("ref-orderitem");
                        if (orderIdNode != null)
                        {
                            if (Convert.ToInt32(orderIdNode.Attributes["id"].Value.Trim()) == orderItemId)//找到了该产品
                            {
                                TotalPriceAfterDiscount = Convert.ToDecimal(orderItemPrice.SelectSingleNode("price").Attributes["gross"].Value);
                                isFindInOrderItem = true;
                                break;
                            }
                        }
                    }

                    if (!isFindInOrderItem)//即在orderItems中没有找到相应的记录,则从ProductPrices中寻找
                    {
                        foreach (XmlNode orderItemPrice in price.SelectNodes(@"productprices/productprice"))
                        {
                            var orderIdNode = orderItemPrice.SelectSingleNode("ref-product");
                            if (orderIdNode != null)
                            {
                                if (orderIdNode.Attributes["id"].Value.Trim() == productID)//找到了该产品
                                {
                                    TotalPriceAfterDiscount = Convert.ToDecimal(orderItemPrice.SelectSingleNode("price").Attributes["gross"].Value);
                                    isFindInOrderItem = true;
                                    IsUnitDiscount = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 得到这一类产品的所以定单
        /// </summary>
        /// <param name="db"></param>
        /// <param name="product"></param>
        /// <param name="xml"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        private List<orderInfo> CreateNewOrderInfoList(newSampleYPDBEntities db, XmlDocument xml, XmlNode product, Tb_Product tb_product, string CtmName, JobSheetSummary_Delivery_Fuji_Info deliveryInfo, out string errMsg, out int intDSC_PRINTCount)
        {
            //同一类产品中的所有定单中只有纸型、纸面、是否色彩优化、照片不同，其它都相同
            errMsg = "";
            List<orderInfo> listOrderInfo = new List<orderInfo>();
            orderInfo newOrderInfo;

            #region 同一类型产品所有的公共尾性
            //double Height = product.Attributes["print-height"] == null ? 0 : Math.Round(Convert.ToDouble(product.Attributes["print-height"].Value) / INCHTOMM, 2);//从mm转化为inch
            //double Width = product.Attributes["print-width"] == null ? 0 : Math.Round(Convert.ToDouble(product.Attributes["print-width"].Value) / INCHTOMM, 2);//从mm转化为inch
            //Height = Height == 0 ? tb_product.Height : Height;
            //Width = Width == 0 ? tb_product.Width : Width;

            double Height = tb_product.Height;
            double Width = tb_product.Width;

            //string OrderProductName = product.Attributes["title-key"].Value;
            string OrderProductName = string.Empty;

            #endregion
            string productID = product.Attributes["id"].Value.Trim();//当从orderItemsPrice中找不到价格时就从productPrice中找到价格,这种一般是折扣价
            XmlNodeList orderItems = product.SelectNodes("orderitem");//一个orderItem代表一个具体的产品

            bool IsPrintProduct = false;
            if (tb_product.ProductName.Contains("DSC_PRINT"))//查看该类产品是否是直出产品,如果是的则该类产品下的所有可用照片都放在一个产品之下
            {
                IsPrintProduct = true;
            }
            int intDSC_PrintCount = 0;
            ArticleInfo newOne = null;
            bool IsUnitDiscount = false;
            if (IsPrintProduct)
            {
                intDSC_PrintCount = orderItems.Count;//累计需要打印索引的照片数量
            }
            foreach (XmlNode orderItem_Product in orderItems)
            {
               
                try
                {
                    decimal TotalPriceBeforeDiscount, discount, TotalPriceAfterDiscount, UnitPrice;

                    GetBeforMoney(xml, orderItem_Product, productID, out TotalPriceBeforeDiscount, out discount, out TotalPriceAfterDiscount, out UnitPrice, out IsUnitDiscount);

                    //先添加每个产品收费明细
                    newOne = new ArticleInfo()
                    {
                        OrderBranch = deliveryInfo.Oi_OrderNum + "-" + orderItem_Product.Attributes["id"].Value.PadLeft(2, '0'),
                        //ProductName = tb_product.ProductName + "(" + tb_product.Width + "X" + tb_product.Height + ")英寸",
                        ProductName = tb_product.ProductName,
                        Quantity = Convert.ToInt32(orderItem_Product.Attributes["quantity"].Value),
                        Discount = discount,
                        TotalPriceAfterDiscount = TotalPriceAfterDiscount,
                        TotalPriceBeforeDiscount = TotalPriceBeforeDiscount,
                        UnitPrice = UnitPrice
                    };

                    newOrderInfo = new orderInfo()
                    {
                        OrderProductId = Convert.ToInt32(orderItem_Product.Attributes["id"].Value),//暂时存放的是order.xml中的ID，用于在生成文件夹路径的时候用
                        CtmName = CtmName,
                        Height = Height,//从mm转化为inch
                        Width = Width,//从mm转化为inch
                        Tb_Product = tb_product,
                        MultiPageNum = 0,
                        OrderProductName = OrderProductName,
                        OrderPath = string.Empty,//产品的路径，即在已开单里面的路径~
                        isCount = 0,
                        Area = 0,//~
                        CompleteTime = DateTime.Now,//~
                        IsEdit = false,
                        OrderType = (int)OrderInfoType.Normal,
                        OrilOrderPath = string.Empty,//
                        PageNum = 0,//
                        ParentProductId = 0,
                        Priority = PRIORITY,
                        status = (int)OrderInfoStatus.Doing,
                        PrePriceCount = 0,//
                        SinglePageNum = 0,
                        Remark = "orderItemdID:" + orderItem_Product.Attributes["id"].Value,
                        ProductType = (int)OrderInfoProductType.NoNeedDesignPrint,
                        productNum = Convert.ToInt32(orderItem_Product.Attributes["quantity"].Value.Trim()),
                        OrderProductCode = "00"
                    };

                    string coverColor = GetCoverColorFromXML(orderItem_Product);
                    if (!string.IsNullOrEmpty(coverColor))
                    {
                        newOrderInfo.Remark += "封面颜色：" + coverColor;
                    }
                }
                catch (Exception ex)
                {
                    errMsg = "在构建OI时出错：" + ex.Message;
                    intDSC_PRINTCount = 0;
                    return null;
                }

                newOrderInfo.OrderProductName = newOrderInfo.Tb_Product.ProductDes + "_" + newOrderInfo.Tb_Product.ProductName;

                #region 一个产品里所有照片公共的属性

                string orderFolder = xmlPath.Substring(0, xmlPath.LastIndexOf("\\"));//得到目录如:d:\a不带后面的“\”     
                string paperTypeName, paperFaceName = string.Empty;
                paperType curPaperType = GetPaperTypeFromXml(db, orderItem_Product, out paperTypeName);
                //paperType curPaperType = db.paperType.FirstOrDefault();//取默认的第一个
                //paperFace curPaperFace = GetPaperFaceFromXml(db, orderItem_Product, out paperFaceName);
                paperFace curPaperFace = db.paperFace.FirstOrDefault();
                if (curPaperType == null)
                {
                    //curPaperType = db.paperType.FirstOrDefault();//取默认的第一个
                    errMsg = "没有这种纸型请先新建纸型，再开单！\n" + paperTypeName;
                    intDSC_PRINTCount = 0;
                    return null;
                }
                if (curPaperFace == null)
                {
                    //curPaperFace = db.paperFace.FirstOrDefault();//暂时

                    errMsg = "系统中没有一种纸面，请添加后再开单!";
                    intDSC_PRINTCount = 0;
                    return null;
                }
                //从order.xml中读取出来的Enhancement
                bool isNeedEnhancement = false;
                if (!tb_product.IsRendered)//非合成的才去取设置的
                {
                    isNeedEnhancement = GetImageEnhancement(orderItem_Product);
                }


                #endregion
                if (IsPrintProduct)
                {
                    newOrderInfo.productNum = 1;//如果是直出的产品,则产品份数为1 
                    if (!GetAllPrintPhotos(db, newOrderInfo, tb_product, orderItems, curPaperType, curPaperFace, isNeedEnhancement, orderFolder, out errMsg))
                    {
                        errMsg = "没有找到照片列表!";
                        intDSC_PRINTCount = 0;
                        return null;
                    }
                    if (IsUnitDiscount)//直出整体打折
                    {
                        int totalNum = newOrderInfo.photoInfo.Sum(p => p.TotalNum) ?? 1;
                        newOne.Quantity = totalNum;
                    }

                    else//直出,不打印或是按单片打折
                    {
                        newOne = null;
                        //将所有的直出的价格加起来
                        foreach (XmlNode orderItem_Product_Price in orderItems)
                        {
                            decimal TotalPriceBeforeDiscount, discount, TotalPriceAfterDiscount, UnitPrice;
                            GetBeforMoney(xml, orderItem_Product_Price, productID, out TotalPriceBeforeDiscount, out discount, out TotalPriceAfterDiscount, out UnitPrice, out IsUnitDiscount);

                            //先添加每个产品收费明细
                            var newOneT = new ArticleInfo()
                             {
                                 OrderBranch = deliveryInfo.Oi_OrderNum + "-" + orderItem_Product_Price.Attributes["id"].Value.PadLeft(2, '0'),
                                 ProductName = tb_product.ProductName,
                                 Quantity = Convert.ToInt32(orderItem_Product_Price.Attributes["quantity"].Value),
                                 Discount = discount,
                                 TotalPriceAfterDiscount = TotalPriceAfterDiscount,
                                 TotalPriceBeforeDiscount = TotalPriceBeforeDiscount,
                                 UnitPrice = UnitPrice
                             };
                            if (newOne == null)
                            {
                                newOne = newOneT;
                            }
                            else
                            {
                                newOne.Quantity += newOneT.Quantity;
                                newOne.Discount += newOneT.Discount;
                                newOne.TotalPriceAfterDiscount += newOneT.TotalPriceAfterDiscount;
                                newOne.TotalPriceBeforeDiscount += newOneT.TotalPriceBeforeDiscount;

                            }
                        }
                    }
                }
                else
                {
                    #region 从XML中读取照片
                    XmlNodeList photoNodes = orderItem_Product.SelectNodes("file");
                    foreach (XmlNode photoNode in photoNodes)
                    {
                        if (!CheckFileIsValid(tb_product, photoNode))
                        {
                            continue;
                        }
                        photoInfo piToAdd = CreateNewPhotoInfo(db, photoNode, curPaperType, curPaperFace, isNeedEnhancement, orderFolder, out errMsg);
                        if (piToAdd == null)
                        {
                            intDSC_PRINTCount = 0;
                            return null;
                        }

                        piToAdd.picPath = newOrderInfo.OrderPath + "\\" + piToAdd.photoName;
                        if (piToAdd.Remark.IndexOf("cover", StringComparison.OrdinalIgnoreCase) > -1)
                        {
                            piToAdd.Width = tb_product.CoverWidth;
                            piToAdd.Height = tb_product.CoverHeight;
                        }
                        else
                        {
                            piToAdd.Width = newOrderInfo.Width;
                            piToAdd.Height = newOrderInfo.Height;
                        }

                        newOrderInfo.photoInfo.Add(piToAdd);
                    }

                    if (!newOrderInfo.OrderProductName.Contains("INDEXPRINT")&&newOrderInfo.photoInfo.Count < 1)
                    {
                        errMsg = "从order.xml中没有找到可用的照片文件存在，请检查order.xml或是产品的是否合成属性是否正确，然后重新再开单！\n" + newOrderInfo.OrderProductName;
                        intDSC_PRINTCount = 0;
                        return null;
                    }
                    else if (newOrderInfo.OrderProductName.Contains("INDEXPRINT"))
                    {
                        newOrderInfo.photoInfo.Add(new photoInfo() {
                            IsModifySize = false,
                            MakeUpNum = 0,
                            OldPicPath = orderFolder + "\\" + "索引.jpg",//在d:\a\1.jpg或是pdf 
                            paperType = curPaperType,
                            imageEnhancement = false,
                            paperFace = db.paperFace.FirstOrDefault(),
                            PhotoBarCode = "00",
                            photoName = "索引.jpg",
                            picPath = "",//需要重新符值~
                            TotalNum = 1,
                            pixHeight = 1,
                            pixWidth = 1,
                            status = (int)PhotoStatus.NoDistributePrinter,//0
                            status2 = 0,
                            userId = 0,
                            Remark = "索引.jpg",
                            printerId = 0, Width=1, Height=1
                        });

                    }
                    #endregion
                }
                deliveryInfo.ArticleList.Add(newOne);
                #region 添加流程

                CreateOrderFlowList(db, newOrderInfo);
                //添加默认的委外商记录
                CreateOutProcessRecord(db, newOrderInfo);

                //再更新相应的orderinfo中的需要信息
                newOrderInfo.PageNum = orderItem_Product.SelectSingleNode("book") == null ? (newOrderInfo.photoInfo.Sum(p => p.TotalNum) ?? 1) : (orderItem_Product.SelectSingleNode("book").Attributes["pages"] == null ? (newOrderInfo.photoInfo.Sum(p => p.TotalNum) ?? 1) : Convert.ToInt32(orderItem_Product.SelectSingleNode("book").Attributes["pages"].Value));
                //newOrderInfo.PageNum = newOrderInfo.photoInfo.Sum(p => p.TotalNum) ?? 1;
                newOrderInfo.Area = Math.Round(newOrderInfo.PageNum * (newOrderInfo.Width * newOrderInfo.Height * 2.54 * 2.54 / 10000), 4);//平方米
                newOrderInfo.CompleteTime = newOrderInfo.WorkOrderFlowList.Max(f => f.PreCompleteTime) ?? newOrderInfo.CompleteTime;
                #endregion

                listOrderInfo.Add(newOrderInfo);

                if (IsPrintProduct)//如果是直出产品则只需要添加一个产品即可
                {
                    break;
                }
            }
            intDSC_PRINTCount = intDSC_PrintCount;
            return listOrderInfo;

        }

        /// <summary>
        /// 如果产品是的DSC_PRINT的产品,则该产品的照片列表所有PRODUCT内的照片
        /// </summary>
        /// <param name="db"></param>
        /// <param name="newOrderInfo"></param>
        /// <param name="tb_product"></param>
        /// <param name="orderItems"></param>
        /// <param name="curPaperType"></param>
        /// <param name="curPaperFace"></param>
        /// <param name="isNeedEnhancement"></param>
        /// <param name="orderFolder"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        private bool GetAllPrintPhotos(newSampleYPDBEntities db, orderInfo newOrderInfo, Tb_Product tb_product, XmlNodeList orderItems, paperType curPaperType, paperFace curPaperFace, bool isNeedEnhancement, string orderFolder, out string errMsg)
        {
            errMsg = string.Empty;

            foreach (XmlNode orderItem_Product in orderItems)
            {
                XmlNodeList photoNodes = orderItem_Product.SelectNodes("file");
                foreach (XmlNode photoNode in photoNodes)
                {
                    if (!CheckFileIsValid(tb_product, photoNode))
                    {
                        continue;
                    }
                    photoInfo piToAdd = CreateNewPhotoInfo(db, photoNode, curPaperType, curPaperFace, isNeedEnhancement, orderFolder, out errMsg);
                    piToAdd.TotalNum = Convert.ToInt32(orderItem_Product.Attributes["quantity"].Value.Trim());//照片的一底多张
                    if (piToAdd == null)
                    {
                        errMsg = "在构建照片" + photoNode.ToString() + "时出错";
                        //出错啦
                        return false;
                    }

                    piToAdd.picPath = newOrderInfo.OrderPath + "\\" + piToAdd.photoName;
                    if (piToAdd.Remark.IndexOf("cover", StringComparison.OrdinalIgnoreCase) > -1)
                    {
                        piToAdd.Width = tb_product.CoverWidth;
                        piToAdd.Height = tb_product.CoverHeight;
                    }
                    else
                    {
                        piToAdd.Width = newOrderInfo.Width;
                        piToAdd.Height = newOrderInfo.Height;
                    }

                    newOrderInfo.photoInfo.Add(piToAdd);
                }
            }

            if (newOrderInfo.photoInfo.Count < 1)
            {
                errMsg = "从order.xml中没有找到可用的照片文件存在，请检查order.xml或是产品的是否合成属性是否正确，然后重新再开单！\n" + newOrderInfo.OrderProductName;
                return false;
            }

            return true;
        }


        /// <summary>
        /// 如果产品有委外节点，并且有默认的委外商，则建立委外记录
        /// </summary>
        /// <returns></returns>
        private void CreateOutProcessRecord(newSampleYPDBEntities db, orderInfo oi)
        {
            if (oi.WorkOrderFlowList.FirstOrDefault(wf => wf.tb_Tech.TechType == (int)TechType.OutProduct) != null)//有委外加工节点
            {
                if (!oi.Tb_Product.Tb_OutShop_ProductCategory.IsLoaded)
                {
                    oi.Tb_Product.Tb_OutShop_ProductCategory.Load();
                }

                var outPMsg = oi.Tb_Product.Tb_OutShop_ProductCategory.FirstOrDefault(op => op.IsDefaultOutShop);

                if (outPMsg != null)//有默认的委外商
                {
                    if (!outPMsg.OutProcessShopReference.IsLoaded)
                    {
                        outPMsg.OutProcessShopReference.Load();
                    }

                    oi.OutProcessRecord.Add(new OutProcessRecord()
                    {
                        CreateTime = DateTime.Now,
                        FetchRemark = "",
                        FetchTime = DateTime.Now.AddHours(outPMsg.NeedTime),
                        OperateUser = db.users.FirstOrDefault().userID,
                        OutRemark = "",
                        Remark = "",
                        PreFetchTime = DateTime.Now.AddHours(outPMsg.NeedTime),
                        users = db.users.FirstOrDefault(),
                        users1 = db.users.FirstOrDefault(),
                        StartProductTime = DateTime.Now,
                        OutProcessShop = outPMsg.OutProcessShop,
                        EndProductTime = DateTime.Now.AddHours(outPMsg.NeedTime),
                        Status = (int)OutProcessRecordStatus.OutWaitFenDui,
                        Status2 = (int)OutProcessRecordStatus2.Wait
                    });

                }

            }
        }

        /// <summary>
        /// 检查文件是否可用的“PHOTO”元素
        /// </summary>
        /// <returns></returns>
        bool CheckFileIsValid(Tb_Product tb_product, XmlNode photoNode)
        {
            var useageAttr = photoNode.Attributes["usage"];
            if (tb_product.IsRendered)//合成产品
            {
                if (useageAttr != null)
                {
                    return useageAttr.Value.StartsWith("rendered/");
                }
                return false;
            }
            else
            {
                if (useageAttr == null)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }


        /// <summary>
        /// 构建产品
        /// </summary>
        /// <param name="db"></param>
        /// <param name="product"></param>
        /// <param name="xml"></param>
        /// <returns></returns>
        //private orderInfo CreateNewOrderInfo(newSampleYPDBEntities db, XmlNode product, XmlDocument xml, out string errMsg)
        //{
        //    errMsg = "";
        //    orderInfo newOrderInfo;
        //    XmlNode addressNode = xml.SelectSingleNode(@"/order/addresses/address");
        //    string strExportName = product.Attributes["exportname"].Value.Trim();

        //    Tb_Product tb_product = db.Tb_Product.FirstOrDefault(p => p.ProductName == strExportName);
        //    if (tb_product == null)
        //    {
        //        errMsg = "产品库中没有该产品，请先添加后重新开单！\n" + strExportName;
        //        return null;
        //    }

        //    try
        //    {
        //        newOrderInfo = new orderInfo()
        //        {
        //            CtmName = addressNode.Attributes["firstname"].Value + addressNode.Attributes["lastname"].Value,
        //            Height = Math.Round(Convert.ToDouble(product.Attributes["print-height"].Value) / INCHTOMM, 2),//从mm转化为inch
        //            Width = Math.Round(Convert.ToDouble(product.Attributes["print-width"].Value) / INCHTOMM, 2),//从mm转化为inch
        //            Tb_Product = tb_product,
        //            MultiPageNum = 0,
        //            OrderProductName = product.Attributes["title-key"].Value,
        //            OrderPath = string.Empty,//产品的路径，即在已开单里面的路径~
        //            isCount = 0,
        //            Area = 0,//~
        //            CompleteTime = DateTime.Now,//~
        //            IsEdit = false,
        //            OrderType = (int)OrderInfoType.Normal,
        //            OrilOrderPath = string.Empty,//
        //            PageNum = 0,//~
        //            ParentProductId = 0,
        //            Priority = PRIORITY,
        //            status = (int)OrderInfoStatus.Doing,
        //            PrePriceCount = 0,//
        //            SinglePageNum = 0,
        //            Remark = product.Attributes["id"].Value,
        //            ProductType = (int)OrderInfoProductType.NoNeedDesignPrint,
        //            productNum = 1,
        //            OrderProductCode = "00"
        //        };

        //    }
        //    catch (Exception ex)
        //    {
        //        errMsg = "在构建OI时出错：" + ex.Message;
        //        return null;
        //    }
        //    newOrderInfo.OrderProductName = newOrderInfo.Tb_Product.ProductName + "_" + newOrderInfo.OrderProductName;

        //    XmlNodeList photoNodes = product.SelectNodes("orderitem");
        //    foreach (XmlNode photoNode in photoNodes)
        //    {
        //        photoInfo piToAdd = CreateNewPhotoInfo(db, photoNode, out errMsg);
        //        if (piToAdd == null)
        //        {
        //            return null;
        //        }

        //        piToAdd.picPath = newOrderInfo.OrderPath + "\\" + piToAdd.photoName;
        //        piToAdd.Width = newOrderInfo.Width;
        //        piToAdd.Height = newOrderInfo.Height;

        //        newOrderInfo.photoInfo.Add(piToAdd);
        //    }

        //    if (newOrderInfo.photoInfo.Count < 1)
        //    {
        //        errMsg = "从order.xml中照片文件存在，请检查后重新再开单！\n" + newOrderInfo.OrderProductName;
        //        return null;
        //    }

        //    CreateOrderFlowList(db, newOrderInfo);

        //    //再更新相应的orderinfo中的需要信息
        //    newOrderInfo.PageNum = newOrderInfo.photoInfo.Sum(p => p.TotalNum) ?? 1;
        //    newOrderInfo.Area = newOrderInfo.PageNum * (newOrderInfo.Width * newOrderInfo.Height * 2.54 * 2.54 / 10000);//平方米
        //    newOrderInfo.CompleteTime = newOrderInfo.WorkOrderFlowList.Max(f => f.PreCompleteTime) ?? newOrderInfo.CompleteTime;
        //    return newOrderInfo;
        //}


        private photoInfo CreateNewPhotoInfo(newSampleYPDBEntities db, XmlNode photoNode, paperType curPaperType, paperFace curPF, bool imageEnhancement, string orderFolder, out string errMsg)
        {
            errMsg = string.Empty;
            string photoName = photoNode.Attributes["name"].Value;
            string remark = "";

            //if (photoName.IndexOf("cover", StringComparison.OrdinalIgnoreCase) < 0)//如果photoName中没有cover，则从useage中查找是否有cover,如果有的话就加到photoName的中前面如cover_photoname
            //{
            if (photoNode.Attributes["usage"] != null)
            {
                string userage = photoNode.Attributes["usage"].Value;
                if (userage.IndexOf("cover", StringComparison.OrdinalIgnoreCase) > -1 || photoName.IndexOf("cover", StringComparison.OrdinalIgnoreCase) > -1)
                {
                    //photoName = "cover_" + photoName;
                    remark = "cover";
                }
            }
            //}

            photoInfo newP;
            try
            {
                newP = new photoInfo()
                {
                    IsModifySize = false,
                    MakeUpNum = 0,
                    OldPicPath = orderFolder + "\\" + photoName,//在d:\a\1.jpg或是pdf 
                    paperType = curPaperType,
                    imageEnhancement = imageEnhancement,
                    paperFace = curPF,
                    PhotoBarCode = "00",
                    photoName = photoName,
                    picPath = "",//需要重新符值~
                    TotalNum = 1,
                    pixHeight = photoNode.Attributes["pixel-height"] == null ? 1 : Convert.ToInt32(photoNode.Attributes["pixel-height"].Value),
                    pixWidth = photoNode.Attributes["pixel-width"] == null ? 1 : Convert.ToInt32(photoNode.Attributes["pixel-width"].Value),
                    status = (int)PhotoStatus.NoDistributePrinter,//0
                    status2 = 0,
                    userId = 0,
                    Remark = photoNode.Attributes["pageIndex"] == null ? "" : ("index:" + photoNode.Attributes["pageIndex"].Value) + "_" + remark,
                    printerId = 0
                };
            }
            catch (Exception ex)
            {
                errMsg = "在构建PI是出错：" + ex.Message;
                return null;
            }

            return newP;
        }

        /// <summary>
        /// 建立照片
        /// </summary>
        /// <param name="db"></param>
        /// <param name="photoNode"></param>
        /// <returns></returns>
        //private photoInfo CreateNewPhotoInfo(newSampleYPDBEntities db, XmlNode photoNode, out string errMsg)//photoNode==Order.xml中的orderItem
        //{
        //    errMsg = string.Empty;
        //    string orderFolder = xmlPath.Substring(0, xmlPath.LastIndexOf("\\"));//得到目录如:d:\a不带后面的“\”
        //    Size st = GetPhotoPixSize(photoNode);
        //    string photoName = GetPhotoName(photoNode);
        //    if (photoName.IndexOf("cover", StringComparison.OrdinalIgnoreCase) < 0)//如果photoName中没有cover，则从useage中查找是否有cover,如果有的话就加到photoName的中前面如cover_photoname
        //    {
        //        string userage = photoNode.Attributes["usage"].Value;
        //        if (userage.IndexOf("cover", StringComparison.OrdinalIgnoreCase) > -1)
        //        {
        //            photoName = "cover_" + photoName;
        //        }
        //    }

        //    string paperTypeName = string.Empty;

        //    paperType curPaperType = GetPaperTypeFromXml(db, photoNode, out paperTypeName);
        //    if (curPaperType == null)
        //    {
        //        errMsg = "没有这种纸型请先新建纸型，再开单！\n" + paperTypeName;
        //        return null;
        //    }
        //    paperFace curPF = db.paperFace.FirstOrDefault();
        //    if (curPF == null)
        //    {
        //        errMsg = "数据库中还没有建立任何一种纸面，请先添加纸面，再重新开单！";
        //        return null;
        //    }
        //    photoInfo newP;
        //    try
        //    {
        //        newP = new photoInfo()
        //        {
        //            IsModifySize = false,
        //            MakeUpNum = 0,
        //            OldPicPath = orderFolder + "\\" + photoName,//在d:\a\1.jpg或是pdf 
        //            paperType = curPaperType,
        //            imageEnhancement = GetImageEnhancement(photoNode),
        //            paperFace = curPF,
        //            PhotoBarCode = "00",
        //            photoName = photoName,
        //            picPath = "",//需要重新符值~
        //            TotalNum = Convert.ToInt32(photoNode.Attributes["quantity"].Value),
        //            pixHeight = st.Height,
        //            pixWidth = st.Width,
        //            status = (int)PhotoStatus.WaitPhotoMove,
        //            status2 = 0,
        //            userId = 0,
        //            Remark = photoName,
        //            printerId = 0
        //        };
        //    }
        //    catch (Exception ex)
        //    {
        //        errMsg = "在构建PI是出错：" + ex.Message;
        //        return null;
        //    }

        //    return newP;
        //}
        /// <summary>
        /// 建立流程
        /// </summary>
        /// <param name="db"></param>
        /// <param name="oi"></param>
        private void CreateOrderFlowList(newSampleYPDBEntities db, orderInfo oi)
        {
            if (oi != null && oi.Tb_Product != null)
            {
                if (!oi.Tb_Product.Tb_FlowTemplate.IsLoaded)
                {
                    oi.Tb_Product.Tb_FlowTemplate.Load();
                }

                DateTime assignTime = DateTime.Now;
                OrderFlowListStatus status = OrderFlowListStatus.Complete;
                int flowS = 1;
                foreach (var ft in db.Tb_FlowTemplate.Where(t => t.Tb_Product.ProuctId == oi.Tb_Product.ProuctId).ToList().OrderBy(f => f.WorkOrder))
                {
                    if (!ft.tb_TechReference.IsLoaded)
                    {
                        ft.tb_TechReference.Load();
                    }
                    oi.WorkOrderFlowList.Add(new WorkOrderFlowList()
                    {
                        AssignTime = assignTime,
                        CompletedTime = assignTime.AddHours(ft.tb_Tech.NeedTime),
                        IsEdit = false,
                        PreCompleteTime = assignTime.AddHours(ft.tb_Tech.NeedTime),
                        ReceiveTime = assignTime,
                        Status = (int)status,
                        tb_Tech = ft.tb_Tech,
                        UserId = 0,
                        WorkOrder = ft.WorkOrder
                    });

                    assignTime = assignTime.AddHours(ft.tb_Tech.NeedTime);
                    if (flowS == 1)
                    {
                        status = OrderFlowListStatus.Useable;
                    }
                    else
                    {
                        status = OrderFlowListStatus.Wait;
                    }
                    flowS++;
                }
            }
        }
        const string OPION = "option";
        /// <summary>
        /// 得到纸型
        /// </summary>
        /// <param name="db"></param>
        /// <param name="photoNode"></param>
        /// <returns></returns>
        private paperType GetPaperTypeFromXml(newSampleYPDBEntities db, XmlNode photoNode, out string paperTypeName)//photoNode==Order.xml中的orderItem
        {
            paperTypeName = string.Empty;
            foreach (XmlNode item in photoNode.ChildNodes)
            {
                if (item.Name == OPION)
                {
                    if (item.Attributes["name"].Value == "paperType")//纸型=orderitem中的<option name="paperType" value="glossy">
                    {
                        paperTypeName = item.Attributes["value"].Value.Trim();
                        string temp = paperTypeName;
                        return db.paperType.FirstOrDefault(p => p.Name == temp);
                    }
                }
            }
            //如果没有找到paperType就默认为matte

            return db.paperType.FirstOrDefault(p => p.Name == "matte");
        }

        /// <summary>
        /// 如果返回string.empty则表示没有
        /// </summary>
        /// <param name="photoNode"></param>
        /// <returns></returns>
        private string GetCoverColorFromXML(XmlNode OrderNode)
        {
            string coverColor = string.Empty;
            foreach (XmlNode item in OrderNode.ChildNodes)
            {
                if (item.Name == OPION)
                {
                    if (item.Attributes["name"].Value.Equals("CoverColor", StringComparison.OrdinalIgnoreCase))//纸型=orderitem中的<option name="paperType" value="glossy">
                    {
                        coverColor = item.Attributes["value"].Value.Trim();
                        break;
                    }
                }
            }
            //如果没有找到paperType就默认为matte

            if (!string.IsNullOrEmpty(coverColor))
            {
                coverColor = coverColor.ToUpper();
                switch (coverColor)
                {
                    case "GREEN": coverColor = "绿色";
                        break;
                    case "BLUE": coverColor = "蓝色";
                        break;
                    case "PINK": coverColor = "粉红色";
                        break;
                    case "RED": coverColor = "红色";
                        break;
                    default:
                        break;
                }
            }

            return coverColor;
        }

        /// <summary>
        /// 得到纸面
        /// </summary>
        /// <param name="db"></param>
        /// <param name="photoNode"></param>
        /// <param name="paperFaceName"></param>
        /// <returns></returns>
        private paperFace GetPaperFaceFromXml(newSampleYPDBEntities db, XmlNode photoNode, out string paperFaceName)//photoNode==Order.xml中的orderItem
        {
            paperFaceName = string.Empty;
            foreach (XmlNode item in photoNode.ChildNodes)
            {
                if (item.Name == OPION)
                {
                    if (item.Attributes["name"].Value == "paperFace")//纸型=orderitem中的<option name="paperFace" value="金背面">
                    {
                        paperFaceName = item.Attributes["value"].Value.Trim();
                        string temp = paperFaceName;
                        return db.paperFace.FirstOrDefault(p => p.Name == temp);
                    }
                }
            }

            return null;
        }

        /// <summary>
        /// 得到图片名称
        /// </summary>
        /// <param name="photoNode"></param>
        /// <returns></returns>
        private string GetPhotoName(XmlNode photoNode)//photoNode==Order.xml中的orderItem
        {
            foreach (XmlNode item in photoNode.ChildNodes)
            {
                if (item.Name == "file")
                {
                    if (IsSuitableFile(item.Attributes["name"].Value))
                    {
                        return item.Attributes["name"].Value;
                    }
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// 获得图片是否需要优化，如果没有找到imageEnhancement则返回FALSE
        /// </summary>
        /// <param name="photoNode"></param>
        /// <returns></returns>
        private bool GetImageEnhancement(XmlNode photoNode)
        {
            foreach (XmlNode item in photoNode.ChildNodes)
            {
                if (item.Name == OPION)
                {
                    if (item.Attributes["name"] != null && item.Attributes["name"].Value == "imageEnhancement")//纸型=orderitem中的<option name="paperType" value="glossy">
                    {
                        try
                        {
                            return Convert.ToBoolean(item.Attributes["value"].Value.Trim());
                        }
                        catch (Exception)
                        {
                            return false;
                        }
                    }
                }
            }

            return false;
        }

        /// <summary>
        /// 得到图片的PIX的宽和高
        /// </summary>
        /// <param name="photoNode"></param>
        /// <returns></returns>
        private Size GetPhotoPixSize(XmlNode photoNode)//photoNode==Order.xml中的orderItem
        {
            foreach (XmlNode item in photoNode.ChildNodes)
            {
                if (item.Name == "file")
                {

                    if (item.Attributes["pixel-height"] != null)
                    {
                        return new Size(Convert.ToInt32(item.Attributes["pixel-width"].Value), Convert.ToInt32(item.Attributes["pixel-height"].Value));
                    }
                }
            }
            return new Size(0, 0);
        }

        /// <summary>
        /// 根据文件名判断是否是jpg\pdf\JPEG\PDF
        /// </summary>
        /// <param name="strPicName"></param>
        /// <returns></returns>
        private bool IsSuitableFile(string strPicName)
        {
            string MB = "jpg/JPG/jpeg/JPEG/pdf/PDF";
            return MB.Contains(strPicName.Substring(strPicName.IndexOf(".") + 1));
        }

        /// <summary>
        /// 将图片移动到已开单目录下
        /// </summary>
        /// <param name="newOrderBag"></param>
        private bool MovePicToOrderedFolder(Tb_OrderBag newOrderBag, out string errMsg)
        {
            errMsg = "";
            if (newOrderBag != null)
            {
                try
                {

                    string strShopAndDatePath = FileDirPathBLL.GetOrveredFolder() + "\\" + newOrderBag.Shop.shopName + "\\" + DateTime.Now.ToShortDateString();
                    //建立"商户/日期/"的文件夹
                    if (!FileBLL.CreateDrictory(strShopAndDatePath))
                    {
                        errMsg = "在创建文件夹时出错！\n" + strShopAndDatePath;
                        return false;
                    }
                    string fujiOrderID = "";
                    int at = newOrderBag.BagName.IndexOf("_");
                    if (at > -1)
                    {
                        fujiOrderID = newOrderBag.BagName.Substring(0, at);
                    }

                    foreach (var oi in newOrderBag.orderInfo)
                    {
                        string strCtmAndProductPath = strShopAndDatePath + "\\" + FileBLL.GetValidateFolderName(oi.CtmName) + "\\" + FileBLL.GetValidateFolderName(fujiOrderID + "_" + oi.OrderProductId + oi.OrderProductName);
                        //strCtmAndProductPath = FileBLL.GetValidateFolderName(strCtmAndProductPath);

                        string strCtmAndProductPathBK = strCtmAndProductPath + "//Backup";
                        if (!FileBLL.CreateDrictory(strCtmAndProductPathBK))
                        {
                            errMsg = "在创建文件夹时出错！\n" + strCtmAndProductPathBK;
                            return false;
                        }

                        oi.OrderPath = strCtmAndProductPath;
                        //建立"客人/产品/Backup/"的文件夹
                        foreach (var pi in oi.photoInfo)
                        {
                            if (pi.photoName.Equals("索引.jpg"))
                            {
                                continue;
                            }
                            pi.picPath = strCtmAndProductPath + "\\" + pi.photoName;
                            //pi.Remark += "_" + oi.CtmName + "\\" + oi.OrderProductName + "\\" + pi.photoName;
                            //移动图片
                            if (!FileBLL.CopyAndDelFile(pi.OldPicPath, pi.picPath))
                            {
                                errMsg = "在移动图片时出错！请检检文件是否存在?\n" + pi.OldPicPath;
                                return false;
                            }
                            try
                            {
                                FileBLL.CopyFileA(pi.picPath, strCtmAndProductPathBK + "\\" + pi.photoName, 0);
                                //移动完成后,如果图片是COVER的需要画上中线或是边角线
                                //if (oi.OrderProductName.IndexOf("CAL", StringComparison.OrdinalIgnoreCase) > -1)//说明是台历,台历的话就不需要画角线
                                //{

                                //}
                                //else//你
                                //{
                                //    if (pi.Remark.IndexOf("cover", StringComparison.OrdinalIgnoreCase) > -1)
                                //    {
                                //        DrawSomeLine(pi.picPath);
                                //    }
                                //}
                                if (NeedDrawLineProducts.Contains(oi.Tb_Product.ProductName) && pi.Remark.IndexOf("cover", StringComparison.OrdinalIgnoreCase) > -1)
                                {
                                    DrawSomeLine(pi.picPath);
                                }


                                //File.Copy(pi.picPath, strCtmAndProductPathBK + "\\" + pi.photoName, true);//备份
                            }
                            catch (Exception)
                            {
                                //复制备份时出错
                            }

                        }

                        FileBLL.CopyFileA(xmlPath, strCtmAndProductPath + "\\order_V2.0_WH.xml", 0);
                    }
                    //将order.xml也移过来
                    //FileBLL.CopyAndDelFile(xmlPath, strShopAndDatePath + "\\" + newOrderBag.orderInfo.FirstOrDefault().CtmName + "\\orer_bk.xml");
                    return true;
                }
                catch (Exception ex)
                {
                    errMsg = ex.Message;
                    return false;
                }
            }
            else
            {
                errMsg = "newOrderBag的NULL";
                return false;
            }
        }

        //需要画角色的几种产品
        private List<string> NeedDrawLineProducts = new List<string>(){"PB_DE_HC_203X203",
                                "PB_DE_HC_203X139",
                                "PB_DE_HC_152X139",
                                "PB_DE_HC_203X203_MC",
                                "PB_DE_HC_203X139_MC",
                                "PB_DE_HC_152X139_MC",
                                "PB_DE_SC_197X136",
                                "PB_DE_SC_197X200",
                                "PB_DC_HC_210X225"    };




        /// <summary>
        /// 给封面画四周的边线和中线
        /// </summary>
        /// <param name="strPicPath"></param>
        private void DrawSomeLine(string strPicPath)
        {
            RasterCodecs.Startup();
            RasterCodecs codes = new RasterCodecs();

            try
            {
                RasterImage image = codes.Load(strPicPath);
                //3mm=30个点,按254的DPI

                // create the graphics container for the image and draw the line
                using (RasterImageGdiPlusGraphicsContainer container = image.CreateGdiPlusGraphics())
                {
                    using (Pen pen = new Pen(Color.Black, 1))
                    {
                        // use anti-alias lines
                        container.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
                        //左上角
                        container.Graphics.DrawLine(pen, new Point(0, 0), new Point(30, 0));
                        container.Graphics.DrawLine(pen, new Point(0, 0), new Point(0, 30));
                        //左下角
                        container.Graphics.DrawLine(pen, new Point(0, image.Height - 30), new Point(0, image.Height));
                        container.Graphics.DrawLine(pen, new Point(0, image.Height - 1), new Point(30, image.Height - 1));
                        //右上角
                        container.Graphics.DrawLine(pen, new Point(image.Width - 30, 0), new Point(image.Width, 0));
                        container.Graphics.DrawLine(pen, new Point(image.Width - 1, 0), new Point(image.Width - 1, 30));
                        //右下角
                        container.Graphics.DrawLine(pen, new Point(image.Width - 1, image.Height - 30), new Point(image.Width - 1, image.Height - 1));
                        container.Graphics.DrawLine(pen, new Point(image.Width - 30, image.Height - 1), new Point(image.Width - 1, image.Height - 1));
                        //上中线边上的二条线6.5mm
                        container.Graphics.DrawLine(pen, new Point(image.Width / 2 - 65, 0), new Point(image.Width / 2 - 65, 30));//中线左边
                        container.Graphics.DrawLine(pen, new Point(image.Width / 2 + 65, 0), new Point(image.Width / 2 + 65, 30));//中线右边
                        //下中线边上的二条线6.5mm
                        container.Graphics.DrawLine(pen, new Point(image.Width / 2 - 65, image.Height), new Point(image.Width / 2 - 65, image.Height - 30));//中线左边
                        container.Graphics.DrawLine(pen, new Point(image.Width / 2 + 65, image.Height), new Point(image.Width / 2 + 65, image.Height - 30));//中线右边
                        codes.Save(image, strPicPath, RasterImageFormat.Jpeg, 24);

                    }
                }
            }
            catch { }
            {
                RasterCodecs.Shutdown();
            }
        }

        #endregion


    }
}
